﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using NuMvvm.Services;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace NuMvvm
{
    public static class ViewModelLocator
    {
        public static bool GetAutoWireViewModel(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoWireViewModelProperty);
        }

        public static void SetAutoWireViewModel(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoWireViewModelProperty, value);
        }

        public static readonly DependencyProperty AutoWireViewModelProperty = DependencyProperty.RegisterAttached("AutoWireViewModel", typeof(bool), typeof(Control), new PropertyMetadata(false, AutoWireViewModel_PropertyChangedCallback));

        private static void AutoWireViewModel_PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue == true)
            {
                var element = d as FrameworkElement;
                if (element != null)
                {
                    element.Loaded += Element_Loaded;
                }
            }
        }

        private static void Element_Loaded(object sender, RoutedEventArgs e)
        {
            var element = sender as FrameworkElement;
            if (element != null)
            {
                ViewModelLocationService.AutowireViewModelForView((IWindow)element);
                element.Loaded -= Element_Loaded;
            }
        }
    }
}
